const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command;  // 这一行必须加

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const now = new Date();

  try {
    // 查询今天是否已打卡
    // 获取当前 UTC 时间
    const now = new Date();
    const localMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // UTC 时间的当天零点
    
    const res = await db.collection('checkins_info')
      .where({
        _openid: openid,
        checkinDate: _.gte(localMidnight)  // 今天之后的数据
      })
      .get();

    if (res.data.length > 0) {
      // 已打过卡
      return {
        success: false,
        message: '今天已经打过卡了'
      };
    }

    // 未打卡，插入打卡记录
    await db.collection('checkins_info').add({
      data: {
        _openid: openid,
        checkinDate: now
      }
    });

    return {
      success: true,
      message: '打卡成功'
    };

  } catch (err) {
    return {
      success: false,
      message: '系统错误',
      error: err
    };
  }
};
